import type { Recordable, UserInfo } from '@vben/types';

import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { getUserInfoApi, loginApi, logoutApi } from '#/api';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();
  const loginLoading = ref(false);

  // 初始化时尝试从 localStorage 恢复
  const userIdData = ref<string | undefined>(
    localStorage.getItem('userId') ?? undefined,
  );

  // 监听 userIdData 变化，持久化到 localStorage
  watch(userIdData, (newVal) => {
    if (newVal) {
      localStorage.setItem('userId', newVal);
    } else {
      localStorage.removeItem('userId');
    }
  });
  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;

      const value = await loginApi(params);
      const { token, userId } = value;
      userIdData.value = userId;
      // 如果成功获取到 accessToken
      const accessToken = token;
      if (accessToken) {
        accessStore.setAccessToken(accessToken);
        await router.push({
          path: '/analytics',
        });
        // 获取用户信息并存储到 accessStore 中
        const fetchUserInfoResult = await fetchUserInfo();
        userInfo = fetchUserInfoResult;

        userStore.setUserInfo(userInfo);

        // console.log('response', response);
        // if ((response as any).returnCode === '200' && response.data) {
        //   userInfo = response as data;
        //   userStore.setUserInfo(userInfo);
        // } else {
        //   console.error(
        //     '获取用户信息失败，返回码:',
        //     (response as any).returnCode,
        //   );
        // }

        // accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push({
                path: '/analytics',
              });
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
    userIdData,
  };
});
